@using Acme.BookStore.FormWhxDto.StorehouseDto
@using Volo.Abp.Application.Dtos
@inject IStorehouseService StorehouseService

<Cascader TItem="ManagementDeptDto"
          TValue="int"
          DataSource="@Departments"
          @bind-Value="@Value"
          ValueName="@nameof(ManagementDeptDto.Id)"
          LabelName="@nameof(ManagementDeptDto.Name)"
          ChildrenName="@nameof(ManagementDeptDto.Children)"
          OnSearch="@HandleSearch"
          ShowSearch="true"
          AllowClear="true"
          Style="width: 100%"
          Placeholder="请选择库管部门"
          ChangeOnSelect="true">
</Cascader>

@code {
    [Parameter]
    public int Value { get; set; }

    [Parameter]
    public EventCallback<int> ValueChanged { get; set; }

    private List<ManagementDeptDto> Departments { get; set; } = new();

    protected override async Task OnInitializedAsync()
    {
        await LoadDepartments();
    }

    private async Task LoadDepartments(string searchText = null)
    {
        if (string.IsNullOrWhiteSpace(searchText))
        {
            // 如果没有搜索文本，加载完整的部门树
            Departments = await StorehouseService.GetManagementDeptTreeAsync();
        }
        else
        {
            // 如果有搜索文本，进行搜索
            var input = new ManagementDeptSearchDto
            {
                MaxResultCount = 10,
                SkipCount = 0,
                Sorting = nameof(ManagementDeptDto.Sort),
                Keyword = searchText,
                OnlyActive = true
            };

            var result = await StorehouseService.SearchManagementDeptAsync(input);
            Departments = result.Items.ToList();
        }

        StateHasChanged();
    }

    private async Task HandleSearch(string searchText)
    {
        await LoadDepartments(searchText);
    }
} 